<template>
  <div class="min-h-screen bg-gray-50 p-6">
    <!-- 页面头部 -->
    <div class="mb-6">
      <div class="flex items-center justify-between">
        <div>
          <h1 class="text-2xl font-bold text-gray-900">专业管理</h1>
          <p class="mt-1 text-sm text-gray-600">管理学校专业信息，支持添加、修改、删除和查询操作</p>
        </div>
        <button
          @click="showAddModal = true"
          class="inline-flex items-center px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded-lg hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition-colors"
        >
          <PlusIcon class="w-4 h-4 mr-2" />
          添加专业
        </button>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6 mb-6">
      <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">专业名称</label>
          <input
            v-model="searchForm.name"
            type="text"
            placeholder="请输入专业名称"
            class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
          />
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">专业代码</label>
          <input
            v-model="searchForm.code"
            type="text"
            placeholder="请输入专业代码"
            class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
          />
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">学院</label>
          <Listbox v-model="searchForm.college">
            <div class="relative">
              <ListboxButton class="relative w-full cursor-default rounded-lg bg-white py-2 pl-3 pr-10 text-left border border-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                <span class="block truncate">{{ searchForm.college || '请选择学院' }}</span>
                <span class="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2">
                  <ChevronUpDownIcon class="h-5 w-5 text-gray-400" aria-hidden="true" />
                </span>
              </ListboxButton>
              <transition
                leave-active-class="transition duration-100 ease-in"
                leave-from-class="opacity-100"
                leave-to-class="opacity-0"
              >
                <ListboxOptions class="absolute z-10 mt-1 max-h-60 w-full overflow-auto rounded-md bg-white py-1 text-base shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none">
                  <ListboxOption value="" class="relative cursor-default select-none py-2 pl-10 pr-4 text-gray-900 hover:bg-blue-100">
                    <span class="block truncate font-normal">全部学院</span>
                  </ListboxOption>
                  <ListboxOption
                    v-for="college in colleges"
                    :key="college"
                    :value="college"
                    v-slot="{ active, selected }"
                    class="relative cursor-default select-none py-2 pl-10 pr-4"
                    :class="active ? 'bg-blue-100 text-blue-900' : 'text-gray-900'"
                  >
                    <span class="block truncate" :class="selected ? 'font-medium' : 'font-normal'">
                      {{ college }}
                    </span>
                    <span v-if="selected" class="absolute inset-y-0 left-0 flex items-center pl-3 text-blue-600">
                      <CheckIcon class="h-5 w-5" aria-hidden="true" />
                    </span>
                  </ListboxOption>
                </ListboxOptions>
              </transition>
            </div>
          </Listbox>
        </div>
        <div class="flex items-end gap-2">
          <button
            @click="handleSearch"
            class="flex-1 px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded-lg hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition-colors"
          >
            <MagnifyingGlassIcon class="w-4 h-4 mr-2 inline" />
            搜索
          </button>
          <button
            @click="handleReset"
            class="px-4 py-2 bg-gray-100 text-gray-700 text-sm font-medium rounded-lg hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 transition-colors"
          >
            重置
          </button>
        </div>
      </div>
    </div>

    <!-- 专业列表 -->
    <div class="bg-white rounded-lg shadow-sm border border-gray-200">
      <div class="px-6 py-4 border-b border-gray-200">
        <div class="flex items-center justify-between">
          <h2 class="text-lg font-medium text-gray-900">专业列表</h2>
          <div class="flex items-center gap-4">
            <span class="text-sm text-gray-500">共 {{ filteredMajors.length }} 个专业</span>
            <div class="flex items-center gap-2">
              <button
                @click="handleBatchDelete"
                :disabled="selectedMajors.length === 0"
                class="px-3 py-1.5 text-sm font-medium text-red-600 bg-red-50 rounded-lg hover:bg-red-100 focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
              >
                <TrashIcon class="w-4 h-4 mr-1 inline" />
                批量删除
              </button>
              <button
                @click="handleExport"
                class="px-3 py-1.5 text-sm font-medium text-green-600 bg-green-50 rounded-lg hover:bg-green-100 focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2 transition-colors"
              >
                <ArrowDownTrayIcon class="w-4 h-4 mr-1 inline" />
                导出
              </button>
            </div>
          </div>
        </div>
      </div>

      <div class="overflow-x-auto">
        <table class="min-w-full divide-y divide-gray-200">
          <thead class="bg-gray-50">
            <tr>
              <th class="px-6 py-3 text-left">
                <input
                  type="checkbox"
                  :checked="selectedMajors.length === filteredMajors.length && filteredMajors.length > 0"
                  @change="handleSelectAll"
                  class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                />
              </th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">专业代码</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">专业名称</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">所属学院</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">学制</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">学位类型</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">在校人数</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
            </tr>
          </thead>
          <tbody class="bg-white divide-y divide-gray-200">
            <tr v-for="major in paginatedMajors" :key="major.id" class="hover:bg-gray-50">
              <td class="px-6 py-4">
                <input
                  type="checkbox"
                  :value="major.id"
                  v-model="selectedMajors"
                  class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                />
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{{ major.code }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ major.name }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ major.college }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ major.duration }}年</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ major.degreeType }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ major.studentCount }}</td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span
                  :class="{
                    'bg-green-100 text-green-800': major.status === '正常',
                    'bg-red-100 text-red-800': major.status === '停招',
                    'bg-yellow-100 text-yellow-800': major.status === '暂停'
                  }"
                  class="inline-flex px-2 py-1 text-xs font-semibold rounded-full"
                >
                  {{ major.status }}
                </span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                <div class="flex items-center gap-2">
                  <button
                    @click="handleEdit(major)"
                    class="text-blue-600 hover:text-blue-900 transition-colors"
                  >
                    <PencilIcon class="w-4 h-4" />
                  </button>
                  <button
                    @click="handleView(major)"
                    class="text-green-600 hover:text-green-900 transition-colors"
                  >
                    <EyeIcon class="w-4 h-4" />
                  </button>
                  <button
                    @click="handleDelete(major)"
                    class="text-red-600 hover:text-red-900 transition-colors"
                  >
                    <TrashIcon class="w-4 h-4" />
                  </button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <!-- 分页 -->
      <div class="px-6 py-4 border-t border-gray-200">
        <div class="flex items-center justify-between">
          <div class="text-sm text-gray-500">
            显示第 {{ (currentPage - 1) * pageSize + 1 }} - {{ Math.min(currentPage * pageSize, filteredMajors.length) }} 条，共 {{ filteredMajors.length }} 条
          </div>
          <div class="flex items-center gap-2">
            <button
              @click="currentPage--"
              :disabled="currentPage === 1"
              class="px-3 py-1 text-sm font-medium text-gray-500 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
            >
              上一页
            </button>
            <span class="px-3 py-1 text-sm font-medium text-gray-700">
              {{ currentPage }} / {{ totalPages }}
            </span>
            <button
              @click="currentPage++"
              :disabled="currentPage === totalPages"
              class="px-3 py-1 text-sm font-medium text-gray-500 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
            >
              下一页
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加/编辑专业弹窗 -->
    <Dialog :open="showAddModal || showEditModal" @close="closeModal" class="relative z-50">
      <div class="fixed inset-0 bg-black/30" aria-hidden="true" />
      <div class="fixed inset-0 flex items-center justify-center p-4">
        <DialogPanel class="w-full max-w-2xl rounded-lg bg-white p-6 shadow-xl">
          <DialogTitle class="text-lg font-medium text-gray-900 mb-4">
            {{ showAddModal ? '添加专业' : '编辑专业' }}
          </DialogTitle>
          
          <form @submit.prevent="handleSubmit" class="space-y-4">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">专业代码 *</label>
                <input
                  v-model="formData.code"
                  type="text"
                  required
                  placeholder="请输入专业代码"
                  class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
                  :class="{ 'border-red-300': errors.code }"
                />
                <p v-if="errors.code" class="mt-1 text-sm text-red-600">{{ errors.code }}</p>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">专业名称 *</label>
                <input
                  v-model="formData.name"
                  type="text"
                  required
                  placeholder="请输入专业名称"
                  class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
                  :class="{ 'border-red-300': errors.name }"
                />
                <p v-if="errors.name" class="mt-1 text-sm text-red-600">{{ errors.name }}</p>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">所属学院 *</label>
                <Listbox v-model="formData.college">
                  <div class="relative">
                    <ListboxButton class="relative w-full cursor-default rounded-lg bg-white py-2 pl-3 pr-10 text-left border border-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                      <span class="block truncate">{{ formData.college || '请选择学院' }}</span>
                      <span class="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2">
                        <ChevronUpDownIcon class="h-5 w-5 text-gray-400" aria-hidden="true" />
                      </span>
                    </ListboxButton>
                    <transition
                      leave-active-class="transition duration-100 ease-in"
                      leave-from-class="opacity-100"
                      leave-to-class="opacity-0"
                    >
                      <ListboxOptions class="absolute z-10 mt-1 max-h-60 w-full overflow-auto rounded-md bg-white py-1 text-base shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none">
                        <ListboxOption
                          v-for="college in colleges"
                          :key="college"
                          :value="college"
                          v-slot="{ active, selected }"
                          class="relative cursor-default select-none py-2 pl-10 pr-4"
                          :class="active ? 'bg-blue-100 text-blue-900' : 'text-gray-900'"
                        >
                          <span class="block truncate" :class="selected ? 'font-medium' : 'font-normal'">
                            {{ college }}
                          </span>
                          <span v-if="selected" class="absolute inset-y-0 left-0 flex items-center pl-3 text-blue-600">
                            <CheckIcon class="h-5 w-5" aria-hidden="true" />
                          </span>
                        </ListboxOption>
                      </ListboxOptions>
                    </transition>
                  </div>
                </Listbox>
                <p v-if="errors.college" class="mt-1 text-sm text-red-600">{{ errors.college }}</p>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">学制 *</label>
                <select
                  v-model="formData.duration"
                  required
                  class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
                >
                  <option value="">请选择学制</option>
                  <option value="2">2年</option>
                  <option value="3">3年</option>
                  <option value="4">4年</option>
                  <option value="5">5年</option>
                </select>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">学位类型 *</label>
                <select
                  v-model="formData.degreeType"
                  required
                  class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
                >
                  <option value="">请选择学位类型</option>
                  <option value="学士">学士</option>
                  <option value="硕士">硕士</option>
                  <option value="博士">博士</option>
                  <option value="专科">专科</option>
                </select>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">状态</label>
                <select
                  v-model="formData.status"
                  class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
                >
                  <option value="正常">正常</option>
                  <option value="停招">停招</option>
                  <option value="暂停">暂停</option>
                </select>
              </div>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">专业描述</label>
              <textarea
                v-model="formData.description"
                rows="3"
                placeholder="请输入专业描述"
                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
              ></textarea>
            </div>
            
            <div class="flex justify-end gap-3 pt-4">
              <button
                type="button"
                @click="closeModal"
                class="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 transition-colors"
              >
                取消
              </button>
              <button
                type="submit"
                :disabled="loading"
                class="px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
              >
                {{ loading ? '保存中...' : (showAddModal ? '添加' : '保存') }}
              </button>
            </div>
          </form>
        </DialogPanel>
      </div>
    </Dialog>

    <!-- 查看专业详情弹窗 -->
    <Dialog :open="showViewModal" @close="showViewModal = false" class="relative z-50">
      <div class="fixed inset-0 bg-black/30" aria-hidden="true" />
      <div class="fixed inset-0 flex items-center justify-center p-4">
        <DialogPanel class="w-full max-w-2xl rounded-lg bg-white p-6 shadow-xl">
          <DialogTitle class="text-lg font-medium text-gray-900 mb-4">
            专业详情
          </DialogTitle>
          
          <div v-if="viewData" class="space-y-4">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">专业代码</label>
                <p class="text-sm text-gray-900">{{ viewData.code }}</p>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">专业名称</label>
                <p class="text-sm text-gray-900">{{ viewData.name }}</p>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">所属学院</label>
                <p class="text-sm text-gray-900">{{ viewData.college }}</p>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">学制</label>
                <p class="text-sm text-gray-900">{{ viewData.duration }}年</p>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">学位类型</label>
                <p class="text-sm text-gray-900">{{ viewData.degreeType }}</p>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">在校人数</label>
                <p class="text-sm text-gray-900">{{ viewData.studentCount }}</p>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">状态</label>
                <span
                  :class="{
                    'bg-green-100 text-green-800': viewData.status === '正常',
                    'bg-red-100 text-red-800': viewData.status === '停招',
                    'bg-yellow-100 text-yellow-800': viewData.status === '暂停'
                  }"
                  class="inline-flex px-2 py-1 text-xs font-semibold rounded-full"
                >
                  {{ viewData.status }}
                </span>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">创建时间</label>
                <p class="text-sm text-gray-900">{{ viewData.createdAt }}</p>
              </div>
            </div>
            <div v-if="viewData.description">
              <label class="block text-sm font-medium text-gray-700 mb-1">专业描述</label>
              <p class="text-sm text-gray-900">{{ viewData.description }}</p>
            </div>
          </div>
          
          <div class="flex justify-end pt-4">
            <button
              @click="showViewModal = false"
              class="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 transition-colors"
            >
              关闭
            </button>
          </div>
        </DialogPanel>
      </div>
    </Dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useAppStore } from '../../stores/app'
import {
  Dialog,
  DialogPanel,
  DialogTitle,
  Listbox,
  ListboxButton,
  ListboxOptions,
  ListboxOption
} from '@headlessui/vue'
import {
  PlusIcon,
  MagnifyingGlassIcon,
  TrashIcon,
  ArrowDownTrayIcon,
  PencilIcon,
  EyeIcon,
  ChevronUpDownIcon,
  CheckIcon
} from '@heroicons/vue/24/outline'

// 使用stores
const appStore = useAppStore()

// 响应式数据
const searchForm = ref({
  name: '',
  code: '',
  college: ''
})

const showAddModal = ref(false)
const showEditModal = ref(false)
const showViewModal = ref(false)
const loading = ref(false)
const selectedMajors = ref([])
const currentPage = ref(1)
const pageSize = ref(10)

const formData = ref({
  code: '',
  name: '',
  college: '',
  duration: '',
  degreeType: '',
  status: '正常',
  description: ''
})

const errors = ref({})
const viewData = ref(null)

// 模拟数据
const majors = ref([
  {
    id: 1,
    code: 'CS001',
    name: '计算机科学与技术',
    college: '计算机学院',
    duration: 4,
    degreeType: '学士',
    studentCount: 1250,
    status: '正常',
    description: '培养具有良好的科学素养，系统地掌握计算机科学与技术的基本理论、基本知识和基本技能的高级专门人才。',
    createdAt: '2024-01-15 10:30:00'
  },
  {
    id: 2,
    code: 'SE002',
    name: '软件工程',
    college: '计算机学院',
    duration: 4,
    degreeType: '学士',
    studentCount: 980,
    status: '正常',
    description: '培养能够从事软件开发、测试、维护和软件项目管理的高级专门人才。',
    createdAt: '2024-01-15 10:35:00'
  },
  {
    id: 3,
    code: 'EE003',
    name: '电子信息工程',
    college: '电子工程学院',
    duration: 4,
    degreeType: '学士',
    studentCount: 756,
    status: '正常',
    description: '培养具备电子技术和信息系统的基础知识，能从事各类电子设备和信息系统的研究、设计、制造、应用和开发的高等工程技术人才。',
    createdAt: '2024-01-15 10:40:00'
  },
  {
    id: 4,
    code: 'ME004',
    name: '机械工程',
    college: '机械工程学院',
    duration: 4,
    degreeType: '学士',
    studentCount: 1100,
    status: '正常',
    description: '培养具备机械设计、制造、自动化基础知识与应用能力的高级工程技术人才。',
    createdAt: '2024-01-15 10:45:00'
  },
  {
    id: 5,
    code: 'BM005',
    name: '工商管理',
    college: '管理学院',
    duration: 4,
    degreeType: '学士',
    studentCount: 890,
    status: '正常',
    description: '培养具备管理、经济、法律及企业管理方面的知识和能力的工商管理学科高级专门人才。',
    createdAt: '2024-01-15 10:50:00'
  },
  {
    id: 6,
    code: 'EN006',
    name: '英语',
    college: '外国语学院',
    duration: 4,
    degreeType: '学士',
    studentCount: 456,
    status: '暂停',
    description: '培养具有扎实的英语语言基础和比较广泛的科学文化知识的外语人才。',
    createdAt: '2024-01-15 10:55:00'
  }
])

const colleges = ref([
  '计算机学院',
  '电子工程学院',
  '机械工程学院',
  '管理学院',
  '外国语学院',
  '数学与统计学院',
  '物理学院',
  '化学学院'
])

// 计算属性
const filteredMajors = computed(() => {
  let result = majors.value
  
  if (searchForm.value.name) {
    result = result.filter(major => 
      major.name.toLowerCase().includes(searchForm.value.name.toLowerCase())
    )
  }
  
  if (searchForm.value.code) {
    result = result.filter(major => 
      major.code.toLowerCase().includes(searchForm.value.code.toLowerCase())
    )
  }
  
  if (searchForm.value.college) {
    result = result.filter(major => major.college === searchForm.value.college)
  }
  
  return result
})

const totalPages = computed(() => {
  return Math.ceil(filteredMajors.value.length / pageSize.value)
})

const paginatedMajors = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredMajors.value.slice(start, end)
})

// 方法
const handleSearch = () => {
  currentPage.value = 1
}

const handleReset = () => {
  searchForm.value = {
    name: '',
    code: '',
    college: ''
  }
  currentPage.value = 1
}

const handleSelectAll = (event) => {
  if (event.target.checked) {
    selectedMajors.value = filteredMajors.value.map(major => major.id)
  } else {
    selectedMajors.value = []
  }
}

const handleEdit = (major) => {
  formData.value = { ...major }
  showEditModal.value = true
}

const handleView = (major) => {
  viewData.value = major
  showViewModal.value = true
}

const handleDelete = async (major) => {
  if (confirm(`确定要删除专业 "${major.name}" 吗？`)) {
    // 模拟删除操作
    const index = majors.value.findIndex(m => m.id === major.id)
    if (index > -1) {
      majors.value.splice(index, 1)
    }
    
    // 移除选中状态
    const selectedIndex = selectedMajors.value.indexOf(major.id)
    if (selectedIndex > -1) {
      selectedMajors.value.splice(selectedIndex, 1)
    }
  }
}

const handleBatchDelete = async () => {
  if (selectedMajors.value.length === 0) return
  
  if (confirm(`确定要删除选中的 ${selectedMajors.value.length} 个专业吗？`)) {
    // 模拟批量删除
    majors.value = majors.value.filter(major => !selectedMajors.value.includes(major.id))
    selectedMajors.value = []
  }
}

const handleExport = () => {
  // 模拟导出功能
  const csvContent = [
    ['专业代码', '专业名称', '所属学院', '学制', '学位类型', '在校人数', '状态'],
    ...filteredMajors.value.map(major => [
      major.code,
      major.name,
      major.college,
      `${major.duration}年`,
      major.degreeType,
      major.studentCount,
      major.status
    ])
  ].map(row => row.join(',')).join('\n')
  
  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = '专业列表.csv'
  link.click()
}

const validateForm = () => {
  errors.value = {}
  
  if (!formData.value.code) {
    errors.value.code = '请输入专业代码'
  } else if (!/^[A-Z]{2}\d{3}$/.test(formData.value.code)) {
    errors.value.code = '专业代码格式不正确（如：CS001）'
  }
  
  if (!formData.value.name) {
    errors.value.name = '请输入专业名称'
  }
  
  if (!formData.value.college) {
    errors.value.college = '请选择所属学院'
  }
  
  return Object.keys(errors.value).length === 0
}

const handleSubmit = async () => {
  if (!validateForm()) return
  
  loading.value = true
  
  try {
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    if (showAddModal.value) {
      // 添加专业
      const newMajor = {
        ...formData.value,
        id: Date.now(),
        studentCount: 0,
        createdAt: new Date().toLocaleString('zh-CN')
      }
      majors.value.unshift(newMajor)
    } else {
      // 编辑专业
      const index = majors.value.findIndex(m => m.id === formData.value.id)
      if (index > -1) {
        majors.value[index] = { ...formData.value }
      }
    }
    
    closeModal()
  } catch (error) {
    console.error('操作失败:', error)
  } finally {
    loading.value = false
  }
}

const closeModal = () => {
  showAddModal.value = false
  showEditModal.value = false
  formData.value = {
    code: '',
    name: '',
    college: '',
    duration: '',
    degreeType: '',
    status: '正常',
    description: ''
  }
  errors.value = {}
}

// 生命周期
onMounted(() => {
  // 设置页面标题
  document.title = '专业管理 - 新生报到服务平台'
})
</script>

<style scoped>
/* 自定义样式 */
.transition-colors {
  transition-property: color, background-color, border-color;
  transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
  transition-duration: 150ms;
}
</style>